package com.jnc.pay.biz.common.service.impl;

import com.jnc.pay.biz.common.mapper.AlipayConfigMapper;
import com.jnc.pay.biz.common.model.AlipayConfig;
import com.jnc.pay.biz.common.service.AlipayConfigService;
import com.jnc.pay.constant.RedisConstant;
import com.jnc.pay.core.config.redis.RedisStore;
import com.jnc.pay.util.convert.JsonUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

/**
 * @Auther: jjn
 * @Date: 2020/5/11 19:20
 * @Desc:
 */
@Slf4j
@Service
public class AlipayConfigServiceImpl implements AlipayConfigService {

    @Resource
    private AlipayConfigMapper alipayConfigMapper;
    @Autowired
    private RedisStore redisStore;

    /**
     * 获取有效的appId和alipay配置关联List
     * @return
     */
    @Override
    public List<AlipayConfig> queryAlipayAppConfig() {
        return alipayConfigMapper.queryAlipayAppConfig();
    }

    /**
     * 根据appId，获取alipay配置信息
     * @param appId
     * @return
     */
    @Override
    public AlipayConfig getAlipayAppConfig(String appId) {
        return alipayConfigMapper.getAlipayAppConfig(appId);
    }

    /**
     * 加载支付宝支付配置到redis
     */
    @Override
    public void loadRedisAlipayConfig() {
        List<AlipayConfig> list = alipayConfigMapper.queryAlipayAppConfig();
        if(list == null || list.size() < 1){
            log.warn("No valid appId with alipay config ...");
            return;
        }
        for (AlipayConfig obj : list){
            //先清空老的缓存数据
            redisStore.del(RedisConstant.ALIPAY_CONFIG + obj.getAppId());
            //再存入新的缓存数据
            redisStore.set(RedisConstant.ALIPAY_CONFIG + obj.getAppId(), JsonUtil.bean2Json(obj));
        }
    }
}
